package com.octopus.core.parser;

import com.google.gson.Gson;
import com.octopus.core.Response;
import com.octopus.core.result.Result;
import com.octopus.core.utils.JsonUtils;
import lombok.NonNull;

/**
 * 快捷JSON转换为实体类型
 *
 * <p>基于GSON
 *
 * @author yang_shoulai@hoperun.com
 * @date 2019/08/05
 */
public class Json2TypeParser<T> extends TextParser {

  private Gson gson;

  private Class<T> typeClass;

  public Json2TypeParser(@NonNull Class<T> typeClass) {
    this(typeClass, null);
  }

  public Json2TypeParser(@NonNull Class<T> typeClass, Gson gson) {
    this.typeClass = typeClass;
    this.gson = gson;
    if (this.gson == null) {
      this.gson = new Gson();
    }
  }

  @Override
  public ParseResult parse(String text, Response response) throws ParseException {
    return ParseResult.me().body(Result.me().obj(JsonUtils.fromJson(text, typeClass, gson)));
  }
}
